// pages/user/user.js
const app = getApp()
const defaultAvatarUrl = '../../images/avatar.png'
const { saveUserInfo } = require('../../api/user')


Page({
  data: {
    userInfo: false,
  },

  onLoad: function (options) {
    app.getUserInfo().then(user => {
      user.avatar = user.avatar || defaultAvatarUrl
      this.setData({
        userInfo: user
      })
    })
    this.loginDialog = this.selectComponent('#loginDialog')
  },

  doLogin() {
    this.loginDialog.show()
  },

  onGetUserInfo(e) {
    this.setData({
      'userInfo.avatar': e.detail.avatarUrl,
      'userInfo.nickname': e.detail.nickName,
    })
    app.getUserInfo().then(userInfo => {
      userInfo.avatar = e.detail.avatarUrl
      userInfo.nickname = e.detail.nickName
      // save user
      saveUserInfo(userInfo).then(response => {
        wx.setStorageSync('user', this.userInfo)
        app.global.user = this.userInfo
      })
    })
  }
  
})